package cn.workreport.util;

import cn.hutool.extra.spring.SpringUtil;
import cn.workreport.modules.common.entity.UserCacheEntity;
import cn.workreport.modules.common.exception.ServiceException;
import cn.workreport.modules.role.entity.Role;
import cn.workreport.modules.users.entity.UserEntity;
import org.springframework.util.ObjectUtils;

public class UserChacheFromToken {

    public static final String USER_CACHE_KEY = "login_user_cache";

    public static final String TOKEN_CACHE_KEY = "login_token_cache";

    public static final String USER_ID_CACHE_KEY = "login_user_id_cache";

    public static void setUserId(Integer userId) {
        ThreadLocalUtil.set(USER_ID_CACHE_KEY, userId);
    }

    public static Integer getUserId() {
        return ThreadLocalUtil.get(USER_ID_CACHE_KEY);
    }

    /**
     *  获取用户 token
     * @return
     */
    public static String getUserToken(){
        Integer userId = getUserId();
        if (ObjectUtils.isEmpty(userId)) {
            return null;
        }
        UserCacheEntity userCacheEntity = getUserCacheEntity(userId);
        return userCacheEntity.getToken();
    }

    /**
     *  获取用户信息
     */
    public static UserEntity getUser() {
        Integer userId = getUserId();
        System.out.println("获取用户信息 ===> userId: " + userId);
        if (ObjectUtils.isEmpty(userId)) {
            return null;
        }
        UserCacheEntity userCacheEntity = getUserCacheEntity(userId);
        return userCacheEntity.getUser();
    }

    /**
     *  获取用户角色
     */
    public static Role getRole() {
        Integer userId = getUserId();
        if (ObjectUtils.isEmpty(userId)) {
            return null;
        }
        UserCacheEntity userCacheEntity = getUserCacheEntity(userId);
        return userCacheEntity.getUserRole();
    }

    /**
     *  删除用户信息
     * @return
     */
    public static void removeUserId() {
        ThreadLocalUtil.remove(USER_ID_CACHE_KEY);
    }

    /**
     *  获取用户名
     * @return
     */
    public static String getUserName(){
        UserEntity userEntity = getUser();
        if (userEntity != null){
            return userEntity.getUsername();
        }
        return null;
    }

    private static UserCacheEntity getUserCacheEntity(Integer userId) {
        if (ObjectUtils.isEmpty(userId)) {
            throw new ServiceException("getUserCacheEntity 参数 userId 不能为空");
        }
        TokenUtil tokenUtil = SpringUtil.getBean("tokenUtil", TokenUtil.class);
        return tokenUtil.getUserCache(userId);
    }

}
